/**
 * 
 */
package edu.arizona.bio5.onto.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;

/**
 * @author pklinov
 *
 */
public class OntologyIterator implements Iterator<OWLOntology> {

	private File m_folder = null;
	private List<File> m_files = new ArrayList<File>();
	private Iterator<File> m_iter = null;
	private OWLOntologyManager m_mgr = null;
	private File m_currFile = null;
	
	private static final String[] ONTOLOGY_FILE_EXT = {".rdf",".owl",".xml"};
	
	public OntologyIterator(String folder) throws Exception {
		
		m_folder = new File(folder);
		
		for (File file : m_folder.listFiles(new FilenameFilter(){

			@Override
			public boolean accept(File dir, String fileName) {
				
				for (String ext : ONTOLOGY_FILE_EXT) {
					
					if (fileName.endsWith(ext)) return true;
				}
				
				return false;
			}
			
		})) {
			
			m_files.add(file);
		}
		
		m_iter = m_files.iterator();
	}
	
	@Override
	public boolean hasNext() {

		return m_iter.hasNext();
	}

	@Override
	public OWLOntology next() {

		m_currFile = m_iter.next();
		m_mgr = OWLManager.createOWLOntologyManager();
		
		try {
			
			System.out.println("Loading " + m_currFile + "... ");
			
			return m_mgr.loadOntologyFromOntologyDocument(m_currFile);
			
		} catch (OWLOntologyCreationException e) {

			e.printStackTrace();
			
			return null;
		}
	}

	public OWLOntologyManager getCurrentManager() {
		
		return m_mgr;
	}
	
	public File getCurrentOntologyFile() {
		
		return m_currFile;
	}
	
	@Override
	public void remove() {

		throw new RuntimeException("Can't remove an ontology from a repo");
	}
}
